<template>
  <!-- 新增部门的弹层 -->
  <!-- close-on-click-modal阻止点击空白关闭弹窗 -->
  <el-dialog :title="ShowTitle" :visible="showDialog" :close-on-click-modal="false" @close="closeDialog" @open="getUserSimpleList">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="refForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="1-10个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-10个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-100个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <div slot="footer">
      <el-button type="primary" size="small" @click="confirmAddDepts">确定</el-button>
      <el-button size="small" @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getUserSimpleListAPI, addDepartmentAPI, getDepartmentDetailAPI, editDepartmentAPI } from '@/api/departments'
export default {
  name: 'AddDepts',
  // 需要传入一个props变量来控制 显示或者隐藏
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    nodeDate: {
      type: Object,
      default: () => {}
    },
    departList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      showTitle: '',
      userList: [],
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur'] },
          { min: 1, max: 10, message: '部门名称要求1-10个字符', trigger: ['blur'] },
          { validator: this.valitadorName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur'] },
          { min: 1, max: 10, message: '部门编码要求1-10个字符', trigger: ['blur'] },
          { validator: this.valitadorCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur'] },
          { min: 1, max: 100, message: '部门介绍要求1-100个字符', trigger: ['blur'] }
        ]
      }
    }
  },
  computed: {
    ShowTitle() {
      return this.form.id ? '编辑部门' : '添加部门'
    }
  },
  methods: {
    async getDepartmentDetail() {
      const { data } = await getDepartmentDetailAPI(this.nodeDate.id)
      this.form = data
    },
    closeDialog() {
      /* this.showDialog = false */
      /* sync放权语法 */
      /* this.$emit('updata:showDialog', false) */
      // 清空绑定在表单域上的数据和校验
      this.$refs.refForm.resetFields()
      // 自己手动清空
      this.form = {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '', // 部门介绍
        pid: ''
      }
      this.$emit('closeDialogFn')
    },
    valitadorName(rule, value, callback) {
      let arr = []
      if (this.form.id) {
        if (value === this.nodeDate.name) {
          callback()
          return
        }
        arr = this.departList.filter(item => item.pid === this.nodeDate.pid)
      } else {
        arr = this.nodeDate.children
      }
      const result = arr.some(item => item.name === value)
      result ? callback(new Error('部门名称不可重复')) : callback()
    },
    valitadorCode(rule, value, callback) {
      if (this.form.id && value === this.nodeDate.code) {
        // 修改逻辑
        callback()
        return
      }
      const result = this.departList.some(item => item.code === value)
      result ? callback(new Error('部门编码不可重复')) : callback()
    },
    // 添加
    async getUserSimpleList() {
      const { data } = await getUserSimpleListAPI()
      this.userList = data
    },
    confirmAddDepts() {
      this.$refs.refForm.validate(async valid => {
        if (!valid) return
        // 说明校验通过了
        if (this.form.id) {
          // 判断什么时候调用修改
          await editDepartmentAPI(this.form)
          this.$message.success('恭喜！部门修改成功')
        } else {
          this.form.pid = this.nodeDate.id
          await addDepartmentAPI(this.form)
          // 添加成功后 成功提示+ 重新获取列表 + 弹框关闭（重置表单）
          this.$message.success('恭喜！部门添加成功')
        }
        this.closeDialog()
        this.$emit('add-success')
      })
    }
  }
}
</script>
